﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;

using TravelSite.DAL;
using TravelSite.DAL.Repositories;
using TravelSite.Entities;
using TravelSite.Code;


namespace TravelSite.Api.Site.Account
{
    public partial class Login : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            LoginUser.LoggingIn += new LoginCancelEventHandler(LoginUser_LoggingIn);
            LoginUser.LoginError += LoginUser_LoginError;
            LoginUser.Authenticate += LoginUser_Authenticate;

            if (!IsPostBack)
            {
                DoRedirectIfLogin();
            }
        }

        private void DoRedirectIfLogin()
        {
            if (User.Identity.IsAuthenticated)
                Response.Redirect("~/Client/TravelPackage.aspx", endResponse: true);
        }
        
        private void LoginUser_Authenticate(object sender, AuthenticateEventArgs e)
        {
            bool validateResult = false;
            string userName = "";

            using (var repo = RepositoryFactory.ResolveRepository<ApiContactRepository>())
            {
                Contact cnt = repo.FindByPin(this.LoginUser.Password);
                if (cnt != null)
                {
                    validateResult = true;
                    userName = cnt.ContactId.ToString();
                }
            }
            
            if (validateResult)
            {
                FormsAuthentication.SetAuthCookie(userName, LoginUser.RememberMeSet);
                Response.Redirect("~/admin/TravelPackage.aspx", endResponse: true);
            }

            e.Authenticated = false;
        }

        private void LoginUser_LoginError(object sender, EventArgs e)
        {
            LoginUser.FindControl("lblError").Visible = true;
        }

        void LoginUser_LoggingIn(object sender, LoginCancelEventArgs e)
        {
        }
    }
}
